package actions;

import gui.MainFrame;
import gui.MyTabbedPane;

import java.awt.event.ActionEvent;
import java.util.Date;
import java.util.Properties;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.Topic;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.swing.AbstractAction;
import javax.swing.JTextField;

import model.Message;
import model.User;
/**
 * U ovoj klasi bi trebalo da se napravi novi message i posalje
 * @author Nikola
 *
 */
@SuppressWarnings("serial")
public class SendMessageAction extends AbstractAction {
	
	JTextField jtf;
	private MessageProducer msgProducer;
	private Connection connection;
	private Session session;
	private Topic topic;
	
	public SendMessageAction(JTextField textField) {
		jtf=textField;
		connectToServer();
	}
	
	public SendMessageAction(JTextField textField, Session session, Topic topic) {
		jtf=textField;
		this.session=session;
		this.topic=topic;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		//connectToServer();
		Message message = new Message();
		
		User user = MainFrame.getInstance().getCurrentUser();
		
		MyTabbedPane mtp = MainFrame.getInstance().getTabbedPane();
		
		String inputText=jtf.getText();
		if(inputText!=null) {
			message.setContent(inputText);
			message.setFrom(user);
			message.setDate(new Date());
			message.setTo(mtp.getCurrentUser());
			// create and publish a message
			ObjectMessage msg;
			try {
				msg = session.createObjectMessage(message);
				msgProducer = session.createProducer(topic);
				msgProducer.send(msg);
				if(mtp.getSelectedIndex()>0)
					mtp.getCurrentChatTab().displayMessage(message);
			} catch (JMSException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			jtf.setText("");
		}
	}
	
	private void connectToServer() {
		try {
			final Properties env = new Properties();
			env.put(Context.INITIAL_CONTEXT_FACTORY,
					"org.jboss.naming.remote.client.InitialContextFactory");
			env.put(Context.PROVIDER_URL, "remote://localhost:4447");
			env.put(Context.SECURITY_PRINCIPAL, "guest");
			env.put(Context.SECURITY_CREDENTIALS, "guestguest");
			Context context = new InitialContext(env);
			ConnectionFactory cf = (ConnectionFactory) context
					.lookup("jms/RemoteConnectionFactory");
			topic = (Topic) context
					.lookup("jms/topic/mojTopic");
			context.close();
			connection = cf.createConnection("guest", "guestguest");
			session = connection.createSession(false,
					Session.AUTO_ACKNOWLEDGE);

			connection.start();		
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

}
